import { createRouter, createWebHistory, RouteRecordRaw, NavigationGuardNext, RouteLocationNormalized } from "vue-router";
import UserLogin from "../views/Login/UserLogin.vue"

// 2. 配置路由
const routes: Array<RouteRecordRaw> = [
    {
        path: "/",
        redirect: "/login"
    },
    {
        path: "/login",
        component: UserLogin,
        name: "login"
    },
    {
        path: "/userInfo",
        component: ()=> import("../views/User/UserInfo.vue"),
        name: "userInfo"
    },
    {
        path: "/home",
        name: "home",
        redirect: "/index",
        component: () => import("../views/Home/HomePage.vue"),
        children: [
            {
                path: "/index",
                name: "index",
                component: () => import("../views/Index/IndexPage.vue")
            },
            {
                path: "/orderList",
                name: "orderList",
                component: () => import("../views/Order/OrderList.vue")
            },
            {
                path: "/completePerson",
                name: "completePerson",
                component: () => import("../views/workingPerson/completePerson.vue")
            },
            {
                path: "/registration",
                name: "registration",
                component: () => import("../views/workingPerson/registration.vue")
            },
            {
                path: "/workingList",
                name: "workingList",
                component: () => import("../views/workingPerson/workingList.vue")
            },
        ]
    }
];
// 1.返回一个 router 实列，为函数，里面有配置项（对象） history
const router = createRouter({
    history: createWebHistory(),
    routes,
});

// 全局前置守卫
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext): void => {
    const token = sessionStorage.getItem('token')

    to.path == "/login" ? token ? next("/home") : next() : token ? next() : next("/login")
})

// 全局后置守卫
// router.afterEach((to: RouteLocationNormalized, from: RouteLocationNormalized): void => {

// })

// 3导出路由   然后去 main.ts 注册 router.ts
export default router